package utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.Toast;

import com.qb.devserv.MainService;
import com.qb.devserv.R;
import com.xuexiang.xui.widget.popupwindow.bar.CookieBar;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import receiver.NotificationReceiver;

public class MyUtil {
    //判断字符串是否为空
    public static boolean isNull(Object s) {
        if (s == null) {
            return true;
        } else if (s.equals("null")) {
            return true;
        } else if (s.equals("")) {
            return true;
        } else if (s.toString().equals("{}")) {
            return true;
        } else if (s.toString().equals("[]")) {
            return true;
        }else if (s.toString().length() <= 0) {
            return true;
        } else {
            return false;
        }
    }
    // toast与log
    public static void showToast(Context ctx,String s) {
        Toast.makeText(ctx, s, Toast.LENGTH_LONG).show();
    }
    public static void showLog(String tag, Object obj) {
        if (!tag.equals("")) System.out.println("******"+tag+"******");
        if (!isNull(obj)) System.out.println(obj);
        // Log.v(tag.equals("")?"":tag, String.valueOf(obj));
    }
    // cookieBar
    public static void showCookieBar(Context ctx,String title,String msg,String flag) {
        String actionStr;
        if (flag.equals("login")) {
            actionStr = "重启应用";
        } else {
            actionStr = "关闭";
        }
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                CookieBar.builder((Activity) ctx)
                        .setTitle(title)
                        .setMessage(msg)
                        .setDuration(-1)
                        .setBackgroundColor(R.color.red_start)
                        .setActionColor(R.color.white)
                        .setTitleColor(R.color.red_end)
                        .setAction(actionStr, view1 -> {
                            if (flag.equals("login")) {
                                System.exit(0);
                            }
                        })
                        .show();
            }
        });
    }
    // 日期格式化
    public static String formatDateTime(Date date) {
        SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss", Locale.getDefault());
        String myDate = format.format(date);
        return myDate;
    }
    // long 转日期字符串
    public static String transferLongToDate(String dateFormat, Long millSec){
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        Date date= new Date(millSec);
        return sdf.format(date);
    }
    // 设备ID
    public static String getDevId() {
        String sn = getSN();
        String rdoVer = String.valueOf(Build.getRadioVersion());
        String rdoVerStr = !rdoVer.contains(",")?rdoVer:rdoVer.substring(0,rdoVer.indexOf(","));
        String brand = Build.BRAND;
        String model = Build.MODEL;
        String devId = sn;
        if (sn.equals("unknown")) {
            devId = model+"@"+brand+"-"+rdoVerStr;
        } else {
            devId = model+"@"+brand+"-"+sn;
        }
        return devId;
    }
    public static String getSN()
    {
        String serial = "unknown";
        try {
            Class<?> clazz = Class.forName("android.os.Build");
            Class<?> paraTypes = Class.forName("java.lang.String");
            @SuppressLint("DiscouragedPrivateApi") Method method = clazz.getDeclaredMethod("getString", paraTypes);
            if (!method.isAccessible()) {
                method.setAccessible(true);
            }
            serial = (String)method.invoke(new Build(), "ro.serialno");
        } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return serial;
    }
    // 启动mainservice服务
    public static void serviceGo(Context ctx) {
        Boolean isRun = isServiceRunning(ctx,"com.qb.devserv.MainService");
        if (isRun){
            if (DevInfoUtil.getBrand().equals(ctx.getString(R.string.invalid_device_key))) {
                MyUtil.showToast(ctx, "服务已经启动了");
            } else {
                MyUtil.showToast(ctx,ctx.getString(R.string.invalid_device_tip));
            }
        } else {
            Intent service = new Intent(ctx, MainService.class);
            MyUtil.showLog("启动服务，当前安卓版本"+Build.VERSION.SDK_INT, "");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                ctx.startForegroundService(service);
            } else {
                ctx.startService(service);
            }
        }
    }
    // 判断服务是否运行
    public static boolean isServiceRunning(Context ctx, final String className) {
        ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> info = activityManager.getRunningServices(Integer.MAX_VALUE);
        if (info == null || info.size() == 0) return false;
        for (ActivityManager.RunningServiceInfo aInfo : info) {
            if (className.equals(aInfo.service.getClassName())) return true;
        }
        return false;
    }
    // 判断activity是否在最前端
    public static boolean isActivityForeground (Context ctx) {
        ActivityManager am = (ActivityManager)ctx.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        if(!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(ctx.getPackageName())) {
            return true ;
        }
        return false ;
    }
    //判断网络是否连接
    public static boolean isConnectIsNormal(Context ctx) {
        String netName = "无网络";
        ConnectivityManager connectivityManager = (ConnectivityManager) ctx
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            netName = info.getTypeName();
        }
        MyUtil.showLog("isConnectIsNormal 当前连接网络",netName);
        if (netName.equals("无网络")) return false;
        else return true;
    }
    //文件夹是否存在 不存在则创建
    public static boolean isFolderExists(String strFolder) {
        File file = new File(strFolder);
        if (file.exists()){
            return true;
        } else{
            if (file.mkdir()) {
                return true;
            } else {
                if (file.exists()) {
                    return true;
                }
                else return false;
            }
        }
    }
    //显示通知
    public static void showNotifaction(Context ctx,int nId,String title,String content,int progress,String flag) {
        if (content.equals("")) content = "状态更新于"+MyUtil.formatDateTime(new Date());
        NotificationUtil nu = new NotificationUtil(ctx);
        NotificationManager manager = nu.getManager();
        Notification notification = nu.setContentIntent(null)
                .setFlags(Notification.FLAG_AUTO_CANCEL)
                .setOnlyAlertOnce(true)
                .setAutoCancel(false)
                .setOngoing(true)
                .getNotification(title, content, R.drawable.icon_baseline_desktop_mac_24);
        if (flag.equals("DOWN_LOAD_ROM")) {
            notification = nu.setContentIntent(null)
                    .setFlags(Notification.FLAG_AUTO_CANCEL)
                    .setOngoing(false)
                    .setProgress(progress)
                    .getNotification(title, content, R.drawable.download);
        }
        if (flag.equals("RECOVERY_VERIFY")) {
            notification = nu.setContentIntent(null)
                    .setFlags(Notification.FLAG_AUTO_CANCEL)
                    .setOngoing(false)
                    .setProgress(progress)
                    .getNotification(title, content, R.drawable.ic_baseline_autorenew_32);
        }
        if (flag.equals("RECOVERY_ERROR")) {
            notification = nu.setContentIntent(null)
                    .setFlags(Notification.FLAG_AUTO_CANCEL)
                    .setOngoing(false)
                    .getNotification(title, content, R.drawable.icon_baseline_info_error_32);
        }
        MyUtil.showLog("showNotifaction flag="+flag, "title="+title);
        if (flag.equals("") && title.equals("服务正在运行")) {
            Intent intent = new Intent(ctx, NotificationReceiver.class);
            intent.setAction("UP_DEVICE_DETAIL");
            PendingIntent pendingIntent;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
            } else {
                pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            }
            notification.contentIntent = pendingIntent;
        }
        manager.notify(nId, notification);
        if (flag.equals("DOWN_LOAD_ROM") || flag.equals("RECOVERY_VERIFY")) {
            if (progress>=100) nu.cancelById(nId);
        }
    }
}
